//
//  YKCompseViewController.m
//  youkan
//
//  Created by 吴高烽 on 16/3/31.
//  Copyright © 2016年 Honsintech. All rights reserved.
//!>  一般属性的创建和赋值都是通过下划线的方式实现，点语法实际是调用相应的getter和setter方法

#import "YKCompseViewController.h"  
//#import "YKTextView.h"  //!> 封装到 YKEmotionTextView.h类中去了
#import "YKEmotionTextView.h"
#import "YKComposeToolBar.h"
#import "YKComposePhotos.h"
#import "YKComposeTool.h"
#import "YKEmotionKeyboard.h"
#import "YKEmotions.h"
@interface YKCompseViewController ()<UITextViewDelegate,YKComposeToolBarDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate>
@property (nonatomic ,weak)YKEmotionTextView *textView;
/** 键盘上的工具视图（相机 图片 @ 话题 表情） */
@property (nonatomic ,weak)YKComposeToolBar *tool;
@property (nonatomic ,weak)YKComposePhotos *photosView;
//@property (nonatomic ,weak)UIBarButtonItem *rightButton;
/** 存放上传发布相片的数组 */
@property (nonatomic ,strong)NSMutableArray *mArrImages;
@property (nonatomic ,strong)YKEmotionKeyboard *emtionKeyboard;
@property (nonatomic ,assign)BOOL swithingKeyboard;
@property (nonatomic ,assign)CGFloat keyboardHeigh;

@end

@implementation YKCompseViewController
-(NSMutableArray *)mArrImages{
    if (!_mArrImages) {
        _mArrImages =[NSMutableArray array];
    }
    return _mArrImages;
}
// 表情键盘
-(YKEmotionKeyboard *)emtionKeyboard{
    if (!_emtionKeyboard) {
        _emtionKeyboard =[[YKEmotionKeyboard alloc]init];
        _emtionKeyboard.width =self.view.width;//如果为0，则不显示键盘
        _emtionKeyboard.height =self.keyboardHeigh;
    }
    return _emtionKeyboard;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor=[UIColor whiteColor];

    [self setUpNavgationBar];
    [self setUpTextView];
    [self setUpToolBar];
    [self setUpPhotosView];
}
#pragma mark -添加子视图
-(void)setUpNavgationBar{
    self.title =@"发送微博";
     //!> 创建导航栏上右侧的发送微博按钮并将按钮设为不可用状态
     self.navigationItem.rightBarButtonItem =[[UIBarButtonItem alloc]initWithTitle:@"发送" style:UIBarButtonItemStyleDone target:self action:@selector(sendBtn)];
     self.navigationItem.rightBarButtonItem.enabled =NO;
//    self.navigationItem.rightBarButtonItem =sendBtn;
//    self.rightButton =sendBtn;
    
    UIBarButtonItem *cancleBtn =[[UIBarButtonItem alloc]initWithTitle:@"取消" style:UIBarButtonItemStyleDone target:self action:@selector(cancleBtn)];
    self.navigationItem.leftBarButtonItem =cancleBtn;
}
-(void)sendBtn{
    if (self.mArrImages.count) {
        [self sendImage];
    }else{
        [self sendTitle];
    }
}
-(void)sendTitle{
    [YKComposeTool composeWithStatus:_textView.text success:^{
        [MBProgressHUD showSuccess:@"发送成功"];
        [self dismissViewControllerAnimated:YES completion:nil];
    } failure:^(NSError *error) {
        YKLog(@"YKCompseViewController line is 80=%@",error);
    }];
}
-(void)sendImage{  //!> 这个只是上传了一张照片
    UIImage *image =self.mArrImages[0];
    NSString *status=_textView.text.length?_textView.text:@"分享图片";
//    self.rightButton.enabled =NO;
    [YKComposeTool composeWithStatus:status image:image success:^{
        [MBProgressHUD showSuccess:@"发送图片成功"];
        [self dismissViewControllerAnimated:YES completion:nil];
//        self.rightButton.enabled =YES;
    } failure:^(NSError *error) {
        [MBProgressHUD showError:@"发送图片失败"];
        YKLog(@"YKCompseViewController line is 68=%@",error);
//        self.rightButton.enabled =YES;
    }];
}
-(void)cancleBtn{
    [self dismissViewControllerAnimated:YES completion:nil];
}

-(void)setUpPhotosView{
    YKComposePhotos *photosView=[[YKComposePhotos alloc]initWithFrame:CGRectMake(0, 80, self.view.width, self.view.height-80)];
    [self.textView addSubview:photosView];
    _photosView =photosView;
}
-(void)showImageView{
    //    UIImagePickerControllerSourceTypePhotoLibrary,
    //    UIImagePickerControllerSourceTypeCamera,
    //    UIImagePickerControllerSourceTypeSavedPhotosAlbum
    UIImagePickerController *imagePicker =[[UIImagePickerController alloc]init];
    imagePicker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
    imagePicker.delegate =self;
    [self presentViewController:imagePicker animated:YES completion:nil];
}
-(void)setUpToolBar{
    CGFloat h =35;
    CGFloat y =self.view.height - h;
    YKComposeToolBar *tool=[[YKComposeToolBar alloc]initWithFrame:CGRectMake(0, y, self.view.width, h)];
    _tool =tool;
    tool.delegate =self;
    [self.view addSubview:tool];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
}
#pragma mark -YKComposeToolBarDelegate
-(void)composeToolBar:(YKComposeToolBar *)toolbar didClickBtn:(YKComposeButtonType)index{
    switch (index) {
        case YKComposeButtonTypeCamera:
        {
            [self showImageView];
        }break;
        case YKComposeButtonTypePicture:{
            YKLog(@"图片");
        }break;
        case YKComposeButtonTypeTrend:{
            YKLog(@"话题");
        }break;
        case YKComposeButtonTypeMention:{
            YKLog(@"提及");
        }break;
        case YKComposeButtonTypeEmotion:{
            [toolbar swithEmotinoAndKeyboard];
            [self swithKeyboard];
            
        }break;
        default:
            break;
    }
}
-(void)swithKeyboard{
    if (self.textView.inputView) {
        self.textView.inputView =nil;
    }else{
        self.textView.inputView =self.emtionKeyboard;
    }
    self.swithingKeyboard=YES;
    [self.textView endEditing:YES];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.textView becomeFirstResponder];
        self.swithingKeyboard=NO;
    });

}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    UIImage *imagef =info[UIImagePickerControllerOriginalImage];
    [self.mArrImages addObject:imagef];
    self.photosView.image =imagef;
    [self dismissViewControllerAnimated:YES completion:nil];
//    self.rightButton.enabled =YES;
}

-(void)setUpTextView{
    YKEmotionTextView *textView=[[YKEmotionTextView alloc]initWithFrame:self.view.bounds];
    textView.placeHolder =@"分享新鲜事~";
    textView.alwaysBounceVertical =YES;
    textView.delegate =self;
    _textView =textView;
    textView.font =[UIFont systemFontOfSize:20];
    [self.view addSubview:textView];
//    监听输入文本
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textChange) name:UITextViewTextDidChangeNotification object:nil];
//    YKEmotionKeyboard *emotionKeyboard =[[YKEmotionKeyboard alloc]init];
//    emotionKeyboard.width =self.view.width;
//    emotionKeyboard.height =216;
//    textView.inputView =emotionKeyboard;
    [YKNotificationCenter addObserver:self selector:@selector(emotionSelectd:) name:YKEmotionSelectedtNotification object:nil];
}
-(void)emotionSelectd:(NSNotification*)noti{
    YKEmotions *emotion =noti.userInfo[YKEmotionSelect];
    [self.textView insertEmotion:emotion];
  
   }
/**
 selectedRange:
 1.本来用来控制textView的文字选中范围
 2.如果selectedRange.length为0，就是textView的光标位置
 关于textView文字的字体
 1.如果是普通文字（text），文字大小由textView.font控制
 2.如果是属性文字（attributedText）,文字大小不受textView.font控制，应该用NSMutableAttributedString- (void)addAttribute:(NSString *)name value:(id)value range:(NSRange)range;设置字体。
 **/
-(void)keyboardChangeFrame:(NSNotification*)noti{
    if (self.swithingKeyboard) return;//如果正在切换键盘，不执行后面内容
    
    CGFloat durtion =[noti.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue];
    CGRect frame =[noti.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    self.keyboardHeigh=frame.size.height;
    if (frame.origin.y==self.view.height) { //没弹出
        [UIView animateWithDuration:durtion animations:^{
            self.tool.transform=CGAffineTransformIdentity;
        }];
    }else{//弹出
        [UIView animateWithDuration:durtion animations:^{
            self.tool.transform =CGAffineTransformMakeTranslation(0, -self.keyboardHeigh);
        }];
    }
    
}
//!> 如果是通过添加标签到textView中并不会调用这个方法
-(void)textChange{
//判断textview有没有内容
    YKLog(@"--%@---",self.textView.text);
    if (_textView.text.length) {
        _textView.HiddenPlaceHolder =YES;
    }else{
        _textView.HiddenPlaceHolder =NO;
    }
    self.navigationItem.rightBarButtonItem.enabled =self.textView.hasText;
}
-(void)viewDidAppear:(BOOL)animated{
    [self.textView becomeFirstResponder];
}
-(void)viewWillDisappear:(BOOL)animated{
    [self.textView endEditing:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self.textView endEditing:YES];
}
-(void)dealloc{
    [[NSNotificationCenter defaultCenter ]removeObserver:self];
}


@end
